package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.GoodsItemAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.Goods;
import com.zmx.doctor.pojo.GoodsOrder;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/11/29  14:00
 * 功 能：搜索药品
 */
public class SearchDrugActivity extends BaseActivity implements GoodsItemAdapter.goodsItemListener {

    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.reView)
    RecyclerView reView;
    @BindView(R.id.registered)
    Button registered;


    private List<GoodsOrder> goods_car;
    private GoodsItemAdapter goodsItemAdapter;
    private List<Goods> goods;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_drug;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        goods_car = new ArrayList<>();
        goods = new ArrayList<>();
        goodsItemAdapter = new GoodsItemAdapter(mActivity);
        goodsItemAdapter.setGoodsItemListeners(this);
        reView.setLayoutManager(new LinearLayoutManager(this));
        reView.setAdapter(goodsItemAdapter);

        title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                searchUsre();

            }

        });
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    goods.clear();
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray array = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < array.length(); i++) {

                            Goods g = gson.fromJson(array.getJSONObject(i).toString(), Goods.class);
                            goods.add(g);

                        }
                        goodsItemAdapter.setListAndNotifyDataSetChanged(goods);//就是设置list然后刷新

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

            }

        }
    };

    public void searchUsre() {

        List<String> ls = new ArrayList<>();
        ls.add(title.getText().toString());
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "searchGoods");
        params.put("data[name]", title.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.make/entry", params, handler, 1, 404);

    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setGoodsItemListener(Goods g) {
        showPhoto(g);
    }


    private Dialog modify_dialogs;//弹出框

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void showPhoto(Goods g) {

        View view;//选择性别的view

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_shopping, null);
        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        TextView name = view.findViewById(R.id.name);
        name.setText("商品名称：" + g.getName());
        TextView desc = view.findViewById(R.id.desc);
        desc.setText("药品描述：" + Html.fromHtml((g.getDescribe()), 10));
        EditText y_number = view.findViewById(R.id.y_number);
        EditText y_sm = view.findViewById(R.id.y_sm);
        EditText e_day = view.findViewById(R.id.e_day);

        TextView regular = view.findViewById(R.id.regular);
        regular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"片/次", "瓶/次", "剂/次"};
                showNotice(regular, items);
            }
        });
        TextView e_rate = view.findViewById(R.id.e_rate);
        e_rate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"每日一次", "每日二次", "每日三次"};
                showNotice(e_rate, items);
            }
        });
        TextView e_usage = view.findViewById(R.id.e_usage);
        e_usage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"口服", "外用", "注射"};
                showNotice(e_usage, items);
            }
        });

        Button submit = view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (y_number.getText().toString().equals("")) {

                    Toast("数量不能为空！");
                    return;

                }

                if (y_sm.getText().toString().equals("")) {

                    Toast("使用说明不能为空！");
                    return;

                }
                if (e_day.getText().toString().equals("")) {

                    Toast("用药时长不能为空！");
                    return;

                }

                GoodsOrder go = new GoodsOrder();
                go.setGoods_id(g.getGoods_id());
                go.setGoods_name(g.getName());
                go.setPrice(g.getPrice());
                go.setNumber(Integer.parseInt(y_number.getText().toString()));
                go.setDay(e_day.getText().toString());
                go.setDescribes(y_sm.getText().toString());
                go.setRate(e_rate.getText().toString());
                go.setUsage(e_usage.getText().toString());
                go.setSpecs("");
                go.setType(0);
                goods_car.add(go);
                registered.setText("( "+goods_car.size()+" )完成");

                modify_dialogs.dismiss();

            }
        });

    }

    private AlertDialog alertDialog1; //信息框

    public void showNotice(TextView textView, String[] items) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mActivity);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }


    @OnClick(R.id.registered)
    public void onViewClicked() {

        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("goods_car", (Serializable) goods_car);
        intent.putExtras(bundle); //放置要传出的数据
        //这里是在Recycleview的适配器里，传了一个Activity才能用方法setResult
        this.setResult(101,intent);
        this.finish();


    }
}
